# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Vulnerabilities::UpdateNamespaceIdsOfVulnerabilityReadsWorker, feature_category: :vulnerability_management do
  describe '#perform' do
    let(:project_id) { Time.now.to_i }

    subject(:run_worker) { described_class.new.perform(project_id) }

    before do
      allow(Vulnerabilities::UpdateNamespaceIdsOfVulnerabilityReadsService).to receive(:execute)
    end

    it 'calls the `Vulnerabilities::UpdateNamespaceIdsOfVulnerabilityReadsService`' do
      run_worker

      expect(Vulnerabilities::UpdateNamespaceIdsOfVulnerabilityReadsService).to have_received(:execute).with(project_id)
    end

    context 'when the service class raises `FailedToObtainLockError`' do
      let(:error) { Gitlab::ExclusiveLeaseHelpers::FailedToObtainLockError.new }

      before do
        allow(Vulnerabilities::UpdateNamespaceIdsOfVulnerabilityReadsService).to receive(:execute).and_raise(error)
        allow(described_class).to receive(:perform_in)
      end

      it 'reschedules the job to run in 2 minutes' do
        run_worker

        expect(described_class).to have_received(:perform_in).with(2.minutes, project_id)
      end
    end
  end

  include_examples 'an idempotent worker' do
    let_it_be(:project) { create(:project) }
    let_it_be(:old_namespace) { create(:namespace) }
    let_it_be(:vulnerability_read) { create(:vulnerability_read, project: project, namespace_id: old_namespace.id) }

    let(:job_args) { project.id }

    it 'changes the `namespace_id` of vulnerability read record' do
      subject

      expect(vulnerability_read.reload.namespace_id).to eql(project.namespace_id)
    end
  end
end
